import { defineStore } from 'pinia';
import * as documentApi from '../../api/documentApi';
import type { Document, DocumentVersion, DocumentQueryParams, DocumentStats } from '../../models/document';

export const documentStore = defineStore('document', {
  state: () => ({
    documents: [] as Document[],
    currentDocument: null as Document | null,
    documentVersions: [] as DocumentVersion[],
    totalCount: 0,
    loading: false,
    error: null as string | null,
  }),

  getters: {
    // 获取个人文档
    personalDocuments: (state) => {
      return state.documents.filter(doc => doc.team_id === 0);
    },

    // 获取团队文档
    teamDocuments: (state) => {
      return state.documents.filter(doc => doc.team_id !== 0);
    },

    // 根据文档类型过滤
    getDocumentsByType: (state) => (type: number) => {
      return state.documents.filter(doc => doc.doc_type === type);
    },

    // 获取文档类型名称
    getDocumentTypeName: () => (type: number) => {
      const typeMap: Record<number, string> = {
        1: '日报',
        2: '周报',
        3: '月报',
        4: '自定义文档'
      };
      return typeMap[type] || '未知类型';
    },

    // 获取文档权限名称
    getPermissionName: () => (permission: number) => {
      const permMap: Record<number, string> = {
        1: '仅查看',
        2: '可编辑',
        3: '可分享'
      };
      return permMap[permission] || '未知权限';
    }
  },

  actions: {
    // 创建文档
    async createDocument(params: {
      doc_title: string;
      doc_type: number;
      team_id?: number;
      doc_content?: string;
      permission?: number;
    }) {
      this.loading = true;
      this.error = null;
      try {
        const res = await documentApi.createDocument(params);
        return res;
      } catch (error: any) {
        this.error = error.message || '创建文档失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取文档列表
    async fetchDocumentList(params?: DocumentQueryParams) {
      this.loading = true;
      this.error = null;
      try {
        const res = await documentApi.getDocumentList(params);
        if (res.code === 200) {
          this.documents = res.data.list || [];
          this.totalCount = res.data.total || 0;
        }
        return res;
      } catch (error: any) {
        this.error = error.message || '获取文档列表失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取文档详情
    async fetchDocumentDetail(docId: number) {
      this.loading = true;
      this.error = null;
      try {
        const res = await documentApi.getDocumentDetail(docId);
        if (res.code === 200) {
          this.currentDocument = res.data;
        }
        return res;
      } catch (error: any) {
        this.error = error.message || '获取文档详情失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 更新文档
    async updateDocument(params: {
      id: number;
      doc_title?: string;
      doc_content?: string;
      permission?: number;
      edit_note?: string;
    }) {
      this.loading = true;
      this.error = null;
      try {
        const res = await documentApi.updateDocument(params);
        if (res.code === 200) {
          // 更新当前文档
          if (this.currentDocument && this.currentDocument.id === params.id) {
            this.currentDocument = { ...this.currentDocument, ...params };
          }
          // 更新文档列表中的对应项
          const index = this.documents.findIndex(doc => doc.id === params.id);
          if (index !== -1) {
            this.documents[index] = { ...this.documents[index], ...params };
          }
        }
        return res;
      } catch (error: any) {
        this.error = error.message || '更新文档失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 删除文档
    async deleteDocument(docId: number) {
      this.loading = true;
      this.error = null;
      try {
        const res = await documentApi.deleteDocument(docId);
        if (res.code === 200) {
          // 从列表中移除
          this.documents = this.documents.filter(doc => doc.id !== docId);
          // 如果是当前文档，清空
          if (this.currentDocument && this.currentDocument.id === docId) {
            this.currentDocument = null;
          }
        }
        return res;
      } catch (error: any) {
        this.error = error.message || '删除文档失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 锁定/解锁文档
    async lockDocument(docId: number, lockStatus: number) {
      this.loading = true;
      try {
        const res = await documentApi.lockDocument(docId, lockStatus);
        if (res.code === 200) {
          // 更新状态
          if (this.currentDocument && this.currentDocument.id === docId) {
            this.currentDocument.edit_status = lockStatus;
          }
          const index = this.documents.findIndex(doc => doc.id === docId);
          if (index !== -1) {
            this.documents[index].edit_status = lockStatus;
          }
        }
        return res;
      } catch (error: any) {
        this.error = error.message || '更新文档锁定状态失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取文档版本列表
    async fetchDocumentVersions(docId: number) {
      this.loading = true;
      try {
        const res = await documentApi.getDocumentVersions(docId);
        if (res.code === 200) {
          this.documentVersions = res.data || [];
        }
        return res;
      } catch (error: any) {
        this.error = error.message || '获取文档版本列表失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取指定版本
    async fetchDocumentVersion(docId: number, version: number) {
      this.loading = true;
      try {
        const res = await documentApi.getDocumentVersion(docId, version);
        return res;
      } catch (error: any) {
        this.error = error.message || '获取文档版本失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 恢复到指定版本
    async revertDocumentVersion(params: {
      doc_id: number;
      version: number;
    }) {
      this.loading = true;
      try {
        const res = await documentApi.revertDocumentVersion(params);
        if (res.code === 200 && this.currentDocument && this.currentDocument.id === params.doc_id) {
          // 重新获取文档详情
          await this.fetchDocumentDetail(params.doc_id);
        }
        return res;
      } catch (error: any) {
        this.error = error.message || '恢复文档版本失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 搜索文档
    async searchDocuments(keyword: string, params?: {
      team_id?: number;
      doc_type?: number;
    }) {
      this.loading = true;
      try {
        const res = await documentApi.searchDocuments(keyword, params);
        if (res.code === 200) {
          this.documents = res.data.list || [];
          this.totalCount = res.data.total || 0;
        }
        return res;
      } catch (error: any) {
        this.error = error.message || '搜索文档失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取团队文档统计
    async fetchTeamDocumentStats(teamId: number): Promise<DocumentStats | null> {
      try {
        const res = await documentApi.getTeamDocumentStats(teamId);
        if (res.code === 200) {
          return res.data;
        }
        return null;
      } catch (error: any) {
        this.error = error.message || '获取团队文档统计失败';
        return null;
      }
    },

    // 清空当前文档
    clearCurrentDocument() {
      this.currentDocument = null;
    },

    // 清空错误信息
    clearError() {
      this.error = null;
    }
  }
});